package com.xh.chat.netty.event;

import com.xh.chat.netty.annotation.EventProcess;
import com.xh.chat.netty.enums.MsgActionEnum;
import org.springframework.context.ApplicationContext;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wen
 * @apiNote EventHandlerFactory
 * @since 2021-08-09
 */
public class EventHandlerFactory {

    private static final Map<Integer, EventHandler> EVENT_HANDLER_MAP = new ConcurrentHashMap<>();

    public static void init(ApplicationContext applicationContext) {
        Collection<EventHandler> abstractOrderProcessors = applicationContext.getBeansOfType(EventHandler.class).values();
        for (EventHandler eventHandler : abstractOrderProcessors) {
            Class<? extends EventHandler> aClass = eventHandler.getClass();
            EventProcess process = aClass.getAnnotation(EventProcess.class);
            if (process != null) {
                EVENT_HANDLER_MAP.put(process.value().getType(), eventHandler);
            }
        }
    }

    public static EventHandler getHandler(Integer eventType) {
        EventHandler eventHandler = EVENT_HANDLER_MAP.get(eventType);
        return eventHandler == null ? EVENT_HANDLER_MAP.get(MsgActionEnum.KEEPALIVE.getType()) : eventHandler;
    }


}
